﻿using System;
using System.IO;
using System.Linq;
using System.Text;

namespace XiphMediaEncoder
{
   public static class PathNormalizer
   {
      public static string NormalizeFilename(string filename)
      {
         return NormalizePath(filename, false);
      }

      public static string NormalizePath(string path)
      {
         return NormalizePath(path, true);
      }

      private static string NormalizePath(string path, bool isPath)
      {
         var sb = new StringBuilder(path);
         foreach (char c in Path.GetInvalidFileNameChars())
         {
            if (c == '\\' && isPath) continue;
            if (c == ':')
            {
               if (sb.Length > 2 && isPath)
               {
                  sb.Replace(":", null, 2, sb.Length - 2);
                  continue;
               }
            }

            sb.Replace(c.ToString(), null);
         }

         return sb.ToString();
      }

      public static bool ContainsInvalidCharInFilename(string filename, out string[] invalidChars)
      {
         return ContainsInvalidChar(filename, false, out invalidChars);
      }

      public static bool ContainsInvalidCharInPath(string path, out string[] invalidChars)
      {
         return ContainsInvalidChar(path, true, out invalidChars);
      }

      private static bool ContainsInvalidChar(string path, bool isPath, out string[] invalidChars)
      {
         var sb = new StringBuilder(path);
         if (isPath)
         {
            sb.Replace("\\", null);
            sb.Replace(":", null, 1, 1);
         }

         invalidChars = sb.ToString().Intersect(Path.GetInvalidFileNameChars()).Cast<string>().ToArray();
         return invalidChars.Length != 0;
      }

      public static bool IsValidRootPath(string path)
      {
         if (path != null && path.Length >= 2)
         {
            if (!path.StartsWith(@"\\"))
            {
               if (path.Length == 2)
                  return (path[1] == ':' && Char.IsLetter(path[0]));

               if (path.Length > 2)
                  return (path[1] == ':' && path[2] == Path.DirectorySeparatorChar && Char.IsLetter(path[0]));
            }
            else
               return path.Length > 2;
         }

         return false;
      }
   }

   public static class TagNormalizer
   {
      public static bool ContainsInvalidChar(string tag, out string[] invalidChars)
      {
         invalidChars = tag.Where(c => c < 30 || c > 125 || c == '=').Cast<string>().ToArray();
         return invalidChars.Length != 0;
      }
   }
}